package com.group.voting_system.config;

import com.group.voting_system.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: xyf
 * @Date: 2019/4/18 10:20
 */

@Configuration
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        HttpSession session = request.getSession();
//        String uri = request.getRequestURI();
//
//        if (session.getAttribute("user") != null){
//            String vote = (String) session.getAttribute("vote");
//            if(vote != null){
//                response.sendRedirect(vote);
//                session.setAttribute("vote", null);
//            }
//            return true;
//        }
//        //将url放入session
//
//        session.setAttribute("vote", uri);
//        response.sendRedirect("/user/login");
//        return false;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //未登录的时候
        if (user == null){
            session.setAttribute("voteUrl", request.getRequestURI());
            response.sendRedirect("/user/login");
            return false;
        }
        //登陆后直接放行,让authController处理登录跳转
        return true;
    }
}
